from django.core.paginator import Paginator
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from goodsapp.models import *
from goodsapp.sers import *


class IndexView(APIView):
    def get(self, request):
        queryset = Cate.objects.all()
        ser = CateSer(queryset, many=True)
        data_list = []
        for item in queryset:
            data = {}
            data['cate'] = CateSer(item).data  # 查找到 分类下的所有商品
            goods_queryset = Goods.objects.filter(cate_id=item.id)  # 通过商品外键id等于分类id
            data['good_list'] = GoodsDetailSer(goods_queryset, many=True).data  # 将商品信息赋值到data字典里
            data_list.append(data)  # 然后将分类和商品赋值的信息合并到列表里进行展示
        return Response(data_list)


class GoodsDetailView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        queryset = Goods.objects.filter(id=id).first()
        ser = GoodsSer(queryset)
        return Response(ser.data)


class GoodsSearchView(APIView):
    def get(self, request):
        num = int(request.GET.get('num', 1))  # 获取页码
        name = request.GET.get('name')  # 获取要搜索的商品名
        queryset = Goods.objects.filter(name__contains=name)  # 根据商品名进行搜索
        paginator = Paginator(queryset, 1)  # 创建分页器
        page_data = paginator.get_page(num)  # 根据页码获取到一页数据
        ser = GoodsDetailSer(page_data, many=True)
        resp = {
            'data': ser.data,
            'num_list': [x for x in paginator.page_range]  # 拼接数据
        }
        return Response(resp)


class GoodsListView(APIView):
    def get(self, request):
        num = request.GET.get('num', 1)  # 获取页码
        id = request.GET.get('id')
        flag = request.GET.get('flag')

        if flag == '1':
            queryset = Goods.objects.filter(cate_id=id)
        elif flag == '2':
            queryset = Goods.objects.filter(cate_id=id).order_by('price')
        elif flag == '3':
            queryset = Goods.objects.filter(cate_id=id).order_by('cat')

        paginator = Paginator(queryset, 1)  # 创建分页器
        pag_data = paginator.get_page(num)  # 根据页码获取到一页数据
        ser = GoodsListSer(pag_data, many=True)  # 创建序列化器
        resp = {
            'data': ser.data,
            'page_list': list(paginator.page_range)
        }
        return Response(resp)
